const crypto = require("node:crypto")
const encodedKey = 'Be00jLyhpqtiRs9gglug7ssGFhG8bBdZx+9Do+W0Aj4=';
const encodedIV = 'AAAAAAAAAAAAAAAAAAAAAA=='
const key = Buffer.from(encodedKey, 'base64');
const iv = Buffer.from(encodedIV, 'base64');
const userId = "2000003"
const encryptedText = '-yBqsN_wSmB91RVUp1RcXA..';
module.exports = {
    decipherFun(encryptedText, res) {
        try {
            const decipher = crypto.createDecipheriv('aes-256-cbc', key, iv)
            const encryptedData = Buffer.from(encryptedText, 'base64')
            let decrypted = decipher.update(encryptedData, 'base64', 'utf8');
            decrypted += decipher.final('utf8');
            return decrypted
        } catch (error) {
            return res.send({ code: 500, msg: "fail", data: "解析错误" });
        }
    },
    async decipherFuns(arr) {
        try {
            const obj = {}
            const arrs = arr.map((item) => {
                const decipher = crypto.createDecipheriv('aes-256-cbc', key, iv)
                const encryptedData = Buffer.from(item, 'base64')
                let decrypted = decipher.update(encryptedData, 'base64', 'utf8');
                decrypted += decipher.final('utf8');
                const sqlcount = `SELECT user_name, user_id, type FROM user WHERE user_id = ${decrypted}`
                return global.query(sqlcount)
            })
            const arrsres = await Promise.all(arrs)
            arrsres.map((item, index) => {
                obj[arr[index]] = item[0]
            })
            return obj
        } catch (error) {
            return 500;
        }
    },
    cipherFun(userId, res) {
        try {
            const cipher = crypto.createCipheriv('aes-256-cbc', key, iv)
            let crypted = cipher.update(userId, 'utf8', 'base64');
            crypted += cipher.final('base64');
            return crypted.replace(/\+/g, '-').replace(/\//g, '_').replace(/\=/g, '.')
        } catch (error) {
            return res.send({ code: 500, msg: "fail", data: "解析错误" });
        }
    },
    cipherFuns(ids, res) {
        try {
            const arrs = ids.map((item) => {
                const cipher = crypto.createCipheriv('aes-256-cbc', key, iv)
                let crypted = cipher.update(item, 'utf8', 'base64');
                crypted += cipher.final('base64');
                return crypted.replace(/\+/g, '-').replace(/\//g, '_').replace(/\=/g, '.')
            })
            return arrs
        } catch (error) {
            return res.send({ code: 500, msg: "fail", data: "解析错误" });
        }

    }
};